package com.example.elmmerchants.Shop_Activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.elmmerchants.R;
import com.example.elmmerchants.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Full_Reduction_Page extends AppCompatActivity {

    LinearLayout set_full_reduction_card_view, set_start_date, set_end_date, add_full_reduction_card_view, create_data;
    TextView how_many_full_reduction, start_date, end_date, how_many_date, is_all_custom, is_just_new_custom;
    Switch is_auto_postponement, is_just_in_open_shop_use;
    CheckBox is_read_and_accept;

    int get_how_many_full_reduction = 0;
    long start_date_second = 0;
    String start_date_text = "", end_date_text = "", email;
    boolean is_just_new_custom_can_use = false, is_finish_upload_date = false;
    List<Full_Reduction_Data> full_reduction_data = new ArrayList<>();
    AlertDialog dialog;

    private class Upload_Date_Thread extends Thread {
        @Override
        public void run() {
            is_finish_upload_date = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "insert into `elm`.`merchant_shop_full_reduction_activity` (email, activity_start_day, activity_end_day, is_auto_postponement, is_just_in_open_shop_use, full_how_dollars_1, subtract_how_dollars_1, full_how_dollars_2, subtract_how_dollars_2, full_how_dollars_3, subtract_how_dollars_3, full_how_dollars_4, subtract_how_dollars_4, full_how_dollars_5, subtract_how_dollars_5, is_just_new_custom) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, email);
                    preparedStatement.setString(2, start_date_text);
                    preparedStatement.setString(3, end_date_text);
                    if (is_auto_postponement.isChecked()) {
                        preparedStatement.setInt(4, 1);
                    }
                    else {
                        preparedStatement.setInt(4, 0);
                    }

                    if (is_just_in_open_shop_use.isChecked()) {
                        preparedStatement.setInt(5, 1);
                    }
                    else {
                        preparedStatement.setInt(5, 0);
                    }

                    int temp = 6;
                    for (int i = 0; i < full_reduction_data.size(); i++) {
                        preparedStatement.setDouble(temp, Double.parseDouble(full_reduction_data.get(i).full_how_many_money.getText().toString()));
                        preparedStatement.setDouble(temp + 1, Double.parseDouble(full_reduction_data.get(i).reduction_how_many_money.getText().toString()));
                        temp += 2;
                    }

                    for (int i = temp; i <= 15; i += 2) {
                        preparedStatement.setDouble(i, -1);
                        preparedStatement.setDouble(i + 1, -1);
                    }

                    if (is_just_new_custom_can_use) {
                        preparedStatement.setInt(16, 1);
                    }
                    else {
                        preparedStatement.setInt(16, 0);
                    }
                    preparedStatement.executeUpdate();
                    is_finish_upload_date = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_finish_upload_date) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dialog.dismiss();
                    Intent intent = new Intent(Full_Reduction_Page.this, Check_All_Activity_Page.class);
                    setResult(1, intent);
                    finish();
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_full_reduction_page);

        email = getIntent().getStringExtra("email");

        set_full_reduction_card_view = findViewById(R.id.set_full_reduction_card_view);
        how_many_full_reduction = findViewById(R.id.how_many_full_reduction);
        set_start_date = findViewById(R.id.set_start_date);
        set_end_date = findViewById(R.id.set_end_date);
        start_date = findViewById(R.id.start_date);
        end_date = findViewById(R.id.end_date);
        how_many_date = findViewById(R.id.how_many_date);
        is_auto_postponement = findViewById(R.id.is_auto_postponement);
        is_just_in_open_shop_use = findViewById(R.id.is_just_in_open_shop_use);
        is_all_custom = findViewById(R.id.is_all_custom);
        is_just_new_custom = findViewById(R.id.is_just_new_custom);
        is_read_and_accept = findViewById(R.id.is_read_and_accept);
        add_full_reduction_card_view = findViewById(R.id.add_full_reduction_card_view);
        create_data = findViewById(R.id.create_data);

        set_start_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Dialog dialog1 = new Dialog(view.getContext());
                dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog1.setContentView(R.layout.set_activity_date);

                DatePicker set_date = dialog1.findViewById(R.id.set_date);
                set_date.setMinDate(System.currentTimeMillis() - 1000);

                TextView save = dialog1.findViewById(R.id.save);
                save.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        start_date_text = "";
                        end_date_text = "";
                        how_many_date.setText("0天");
                        end_date.setText("请选择日期");
                        if (set_date.getMonth() + 1 < 10 && set_date.getDayOfMonth() < 10) {
                            start_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                        }
                        else if (set_date.getMonth() + 1 < 10) {
                            start_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                        }
                        else if (set_date.getDayOfMonth() < 10) {
                            start_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                        }
                        else {
                            start_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                        }
                        start_date.setText(start_date_text);
                        dialog1.dismiss();
                    }
                });

                dialog1.show();
                dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 1500);
                dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                dialog1.getWindow().setGravity(Gravity.BOTTOM);
            }
        });
        
        set_end_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (start_date_text.isEmpty()) {
                    Toast.makeText(Full_Reduction_Page.this, "请设置起始日期", Toast.LENGTH_SHORT).show();
                }
                else {
                    Dialog dialog1 = new Dialog(view.getContext());
                    dialog1.requestWindowFeature(Window.FEATURE_NO_TITLE);
                    dialog1.setContentView(R.layout.set_activity_date);

                    DatePicker set_date = dialog1.findViewById(R.id.set_date);
                    DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                    String temp = start_date_text;
                    try {
                        Date date = df.parse(temp);
                        start_date_second = date.getTime();
                        set_date.setMinDate(start_date_second + 86400000);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }

                    TextView save = dialog1.findViewById(R.id.save);
                    save.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            end_date_text = "";
                            if (set_date.getMonth() + 1 < 10 && set_date.getDayOfMonth() < 10) {
                                end_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                            }
                            else if (set_date.getMonth() + 1 < 10) {
                                end_date_text += set_date.getYear() + "/" + "0" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                            }
                            else if (set_date.getDayOfMonth() < 10) {
                                end_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + "0" + set_date.getDayOfMonth();
                            }
                            else {
                                end_date_text += set_date.getYear() + "/" + (set_date.getMonth() + 1) + "/" + set_date.getDayOfMonth();
                            }
                            end_date.setText(end_date_text);
                            DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
                            String temp1 = start_date_text;
                            String temp2 = end_date_text;
                            try {
                                Date date1 = df.parse(temp1);
                                Date date2 = df.parse(temp2);
                                how_many_date.setText(String.valueOf((int) ((date2.getTime() - date1.getTime()) / 86400000)) + "天");
                            } catch (ParseException e) {
                                throw new RuntimeException(e);
                            }
                            dialog1.dismiss();
                        }
                    });

                    dialog1.show();
                    dialog1.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, 1500);
                    dialog1.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                    dialog1.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation;
                    dialog1.getWindow().setGravity(Gravity.BOTTOM);
                }
            }
        });

        is_all_custom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                is_all_custom.setTextColor(Color.BLACK);
                is_just_new_custom_can_use = false;
                is_just_new_custom.setTextColor(Color.rgb(128, 128, 128));
            }
        });

        is_just_new_custom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                is_just_new_custom.setTextColor(Color.BLACK);
                is_just_new_custom_can_use = true;
                is_all_custom.setTextColor(Color.rgb(128, 128, 128));
            }
        });

        add_full_reduction_card_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (get_how_many_full_reduction < 5) {
                    get_how_many_full_reduction += 1;
                    how_many_full_reduction.setText("" + get_how_many_full_reduction);
                    Full_Reduction_Data s = new Full_Reduction_Data();
                    View view1 = LayoutInflater.from(view.getContext()).inflate(R.layout.set_full_reduction_view, null);
                    s.view = view1;
                    EditText full_how_many_money = view1.findViewById(R.id.full_how_many_money);
                    EditText reduction_how_many_money = view1.findViewById(R.id.reduction_how_many_money);
                    s.full_how_many_money = full_how_many_money;
                    s.reduction_how_many_money = reduction_how_many_money;
                    ImageView delete_this_view = view1.findViewById(R.id.delete_this_view);
                    delete_this_view.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            get_how_many_full_reduction -= 1;
                            how_many_full_reduction.setText("" + get_how_many_full_reduction);
                            set_full_reduction_card_view.removeView(view1);
                            for (int i = 0; i < full_reduction_data.size(); i++) {
                                if (view1 == full_reduction_data.get(i).view){
                                    full_reduction_data.remove(i);
                                    break;
                                }
                            }
                        }
                    });

                    full_reduction_data.add(s);
                    set_full_reduction_card_view.addView(view1);
                }
                else {
                    Toast.makeText(Full_Reduction_Page.this, "最多只可创建5个", Toast.LENGTH_SHORT).show();
                }
            }
        });

        create_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                boolean is_can_upload = true;
                boolean is_sort = true;
                double number = -1;
                for (int i = 0; i < full_reduction_data.size(); i++) {
                    if (full_reduction_data.get(i).reduction_how_many_money.getText().toString().isEmpty() || full_reduction_data.get(i).full_how_many_money.getText().toString().isEmpty()) {
                        is_can_upload = false;
                        break;
                    }
                    else if (Double.parseDouble(full_reduction_data.get(i).full_how_many_money.getText().toString()) < number) {
                        is_sort = false;
                        break;
                    }
                    number = Double.parseDouble(full_reduction_data.get(i).full_how_many_money.getText().toString());
                }

                if (!is_sort) {
                    Toast.makeText(Full_Reduction_Page.this, "请令阶梯由小至大排列", Toast.LENGTH_SHORT).show();
                }
                else if (!is_can_upload || start_date_text.isEmpty() || end_date_text.isEmpty() || full_reduction_data.isEmpty()) {
                    Toast.makeText(Full_Reduction_Page.this, "请输入所有数据", Toast.LENGTH_SHORT).show();
                }
                else if (!is_read_and_accept.isChecked()) {
                    Toast.makeText(Full_Reduction_Page.this, "请确认已阅读并同意协议", Toast.LENGTH_SHORT).show();
                }
                else {
                    set_dialog();
                    Upload_Date_Thread uploadDateThread = new Upload_Date_Thread();
                    uploadDateThread.start();
                }
            }
        });
    }

    public void set_dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        LayoutInflater inflater1 = LayoutInflater.from(this);
        builder.setView(inflater1.inflate(R.layout.loading, null));
        builder.setCancelable(false);

        dialog = builder.create();
        dialog.show();
    }
}